var GameWorldLayer = cc.Layer.extend({


    whoIsAtt: true,//true is hero attack,false is the enemy attack
    hero: null,
    enemy: null,
    currentHero: 0,
    currentEnemy: 0,//current Enemy also mean checkpoint
    enemyTotal: enemyArray.length,
    heroTotal: heroArray.length,
    bg: null,
    //per ten checkpoint ,change bg and bgmusic
    isOpenEffect: true,
    isAutoFight: false,
//    isAutoFight: true,
    isFightOnce:false,
    //hasOpenbgMusic:false,
    self: null,
    blink:null,
//    gameRes:{
//        money:0,
//
//    },
    ctor: function () {
        this._super();


        //this.self = this;
        document.body.style.background = "#fff";

        //cc.EventListener.MOUSE
        
        cc.MenuItemFont.setFontName("Times New Roman");
        cc.MenuItemFont.setFontSize(30);

        this.blink = cc.blink(0.2, 1);

        //add bg
        this.bg = new cc.Sprite(res.Image1_jpg);
        this.bg.setOpacity(950);
        //maybe it will be encapsulation
        var scaleX = size.width / this.bg.width;
        var scaleY = size.height / this.bg.height;
        this.bg.attr({
            anchorX: 0,
            anchorY: 0,
            scaleX: scaleX,
            scaleY: scaleY,
        });
        this.addChild(this.bg);
        //add bg musci
        cc.audioEngine.playMusic(res.gameMusic_mp3);
        if (g.isLoad) {
            //load game
            var heroText = g.storage.getItem("hero");
            heroJson = JSON.parse(heroText);
            this.currentEnemy = g.storage.getItem("currentEnemy");
            this.createHero(heroJson);
        } else {
            //new game
            this.createHero(heroArray[this.currentHero]);
        }
        //new enemy
        this.createEneny(enemyArray[this.currentEnemy]);

        //add btn for open and close music
        var startNormal = new cc.MenuItemImage(res.start_png, res.start_png);
        var startSelected = new cc.MenuItemImage(res.pause_png, res.pause_png);
        var musicButton = new cc.MenuItemToggle(startNormal, startSelected, this.controlMusic, this);
        var musicMenu = new cc.Menu(musicButton);
        musicMenu.attr({
            x: size.width - size.width / 32,
            y: size.height - size.width / 21,
            //x:size.width-30,
            //y:size.height-30,
        });
        this.addChild(musicMenu);
/*
--------------autoFight ,shop, magic tree scene--------------------------------
 */
        //autoFight
        var autoFight = new cc.MenuItemImage(res.autoAck_png, res.autoAck_png);
        var autoFightSelected = new cc.MenuItemImage(res.autoAck2_png, res.autoAck2_png);
        var autoFightButton = new cc.MenuItemToggle(autoFight, autoFightSelected, this.autoFight, this);
        var autoFightBtnMenu = new cc.Menu(autoFightButton);
        autoFightBtnMenu.attr({
            x: size.width / 15,
            y: size.height - size.height / 8,
        });
        this.addChild(autoFightBtnMenu);

        //////////////////
        var shopBtn = new ccui.Button(res.shop_png);
        shopBtn.attr({
            name:"shopBtn",
            x: 200,
            y: size.height - size.height / 8,
//            x: size.width / 2 + size.width / 4,
//            y: size.height / 2 - size.width / 16 ,
//            scaleX: 0.3,
//            scaleY: 0.3,
        });
        shopBtn.addClickEventListener(this.shopShow, this);
        this.addChild(shopBtn);
        //////
        var skillTreeBtn = new ccui.Button(res.skill_png);
        skillTreeBtn.attr({
            name:"skillBtn",
            x: 350,
            y: size.height - size.height / 8,
//            x: size.width / 2 + size.width / 4,
//            y: size.height / 2 - size.width / 16 ,
//            scaleX: 0.3,
//            scaleY: 0.3,
        });
        skillTreeBtn.addClickEventListener(this.skillShow, this);
        this.addChild(skillTreeBtn);
/*
-------------------up down btn------------------------------------------
 */
        var upStair = new cc.Sprite(res.up_png);
        var upStairSelected = new cc.Sprite(res.upSelected_png);
        var upStairMenuItem = new cc.MenuItemSprite(
            upStair,
            upStairSelected,
            this.upStair, this);
        upStairMenuItem.attr({
            x: size.width / 2 - size.width / 4,
            y: size.width / 16,
            //x:size.width/2 - 240,
            //y:60,
            scaleX: 0.1,
            scaleY: 0.1,
        });
        var upStairMenu = new cc.Menu(upStairMenuItem);
        this.addChild(upStairMenu, 1, g.upStairMenuTag);

        var downStair = new cc.Sprite(res.down_png);
        var downStairSelected = new cc.Sprite(res.downSelected_png);
        var downStairMenuItem = new cc.MenuItemSprite(
            downStair,
            downStairSelected,
            this.downStair, this);
        downStairMenuItem.attr({
            x: size.width / 2 - size.width / 4,
            //x:size.width/2 - 240,
            //y:0,
            scaleX: 0.1,
            scaleY: 0.1,
        });
        var downStairMenu = new cc.Menu(downStairMenuItem);
        this.addChild(downStairMenu, 1, g.downStairMenuTag);

        var upHeroBtn = new ccui.Button(res.up_png, res.upSelected_png);

        upHeroBtn.attr({
            x: size.width / 5,
            y: size.height / 2 + size.width / 16,
            //x: 192,
            //y:340,
            scaleX: 0.1,
            scaleY: 0.1,
        });
        upHeroBtn.addClickEventListener(this.upHero);
        this.addChild(upHeroBtn, 1, g.upHeroBtnTag);

        var downHeroBtn = new ccui.Button(res.down_png, res.downSelected_png);
        downHeroBtn.attr({
            x: size.width / 5,
            y: size.height / 2,
            //x: 192,
            //y:320,
            scaleX: 0.1,
            scaleY: 0.1,
        });
        downHeroBtn.addClickEventListener(this.downHero);
        this.addChild(downHeroBtn, 1, g.downHeroBtnTag);

/*
-----------------propertyDetail scene---------------------------------
 */

        var HeroPropertyDetailBtn = new ccui.Button(res.property_png);
        HeroPropertyDetailBtn.attr({
            name:'HeroPropertyDetailBtn',
            x: size.width / 5,
            y: size.height / 2 - size.width / 16 ,
            //x: 192,
            //y:340,
            scaleX: 0.3,
            scaleY: 0.3,
        });
        HeroPropertyDetailBtn.addClickEventListener(this.propertyDetailShow, this);
        this.addChild(HeroPropertyDetailBtn);
        //
        var enemyPropertyDetailBtn = new ccui.Button(res.property_png);
        enemyPropertyDetailBtn.attr({
            name:"enemyPropertyDetailBtn",
            x: size.width / 2 + size.width / 4,
            y: size.height / 2 - size.width / 16 ,
            //x: 192,
            //y:340,
            scaleX: 0.3,
            scaleY: 0.3,
        });
        enemyPropertyDetailBtn.addClickEventListener(this.propertyDetailShow, this);
        this.addChild(enemyPropertyDetailBtn);
/*
--------------FightOnce, magic, prop  layer----------------------------------------------
 */
        ///////////////////
        var FightOnceBtn = new ccui.Button(res.property_png);
        FightOnceBtn.attr({
            name:"FightOnceBtn",
//            x: size.width / 2 + size.width / 4,
//            y: size.height / 2 - size.width / 16 ,
//            scaleX: 0.3,
//            scaleY: 0.3,
        });
        FightOnceBtn.addClickEventListener(this.FightOnce, this);
        this.addChild(FightOnceBtn);

//        cc.director.pushScene();
        //this.scheduleUpdate();
        //2 second
        this.schedule(this.Myupdate, 2, cc.REPEAT_FOREVER);

    },
    Myupdate: function (dt) {
        var self = this;
        //no AtoFight and no FightOnce,  so no attack
        if (!this.isAutoFight && !this.isFightOnce) {
            return;
        }
        if (this.whoIsAtt) {
            this.hero.attack(this.enemy);

            //attack sound effect
            if (this.isOpenEffect) {
                cc.audioEngine.playEffect(res.heroAtt_mp3, false);
            }

            //attack effect,a picture of  knife blink
            this.heroAttackEffect.setVisible(1);
            setTimeout(function () {
                self.heroAttackEffect.setVisible(0);
            }, 200);
            //enemy blink
            this.enemy.mySprite.runAction(this.blink);

            this.enemy.hpText.initWithString('hp:' + this.enemy.hp+"/"+this.enemy.hpMax);
            if (this.enemy.hp <= 0) {
                //should be delay ,not write
                //enemy dead music effect ,not write

                //+exp,
                this.hero.addExp(this.enemy.exp);
                this.hero.expText.initWithString('exp:' + this.hero.exp);

                this.hero.hp = this.hero.hpMax;
                this.hero.hpText.initWithString('hp:' + this.hero.hp+"/"+this.hero.hpMax);
                //next enemy and shack the screen
                this.bg.runAction(this.blink);
                this.currentEnemy++;
                if (this.currentEnemy > this.enemyTotal) {
                    //win the whole ganme

                } else {
                    //next checkpoint
                    this.save();
                    this.createEneny(enemyArray[this.currentEnemy]);
                }
            }
            //if (this.hero.hp <= 0) {

            //}
            //enemy attakc
        } else {
            if (this.isOpenEffect) {
                cc.audioEngine.playEffect(res.enemyAtt_mp3, false);
            }
            this.enemyAttackEffect.setVisible(1);
            setTimeout(function () {
                self.enemyAttackEffect.setVisible(0);
            }, 200);
            this.hero.mySprite.runAction(this.blink);


            this.enemy.attack(this.hero);
            this.hero.hpText.initWithString('hp:' + this.hero.hp+"/"+this.hero.hpMax);
            if (this.hero.hp <= 0) {
                //gameover
                //alert("you dead");
                cc.audioEngine.playEffect(res.dead_wav, false);
                ////dead scene ,no wirting

                var transition = new cc.TransitionCrossFade(1, new GameCartoonScene());
                cc.director.runScene(transition);
            }

            this.isFightOnce = false;
        }
        this.whoIsAtt = !this.whoIsAtt;

    },
    autoFight: function (obj) {
        if (obj._selectedIndex==0) {
            this.isAutoFight = false;
        } else {
            this.isAutoFight = true;
        }
    },

    createEneny: function (enemyJson) {

        //temporary remove鍜宎dd锛宻houle be add a pool
        //        * var sp = new cc.Sprite("a.png");
//        * this.addChild(sp);
//        * cc.pool.putInPool(sp);
//        *
//        * cc.pool.getFromPool(cc.Sprite, "a.png");
        if (this.enemy) {
            this.removeChild(this.enemy.mySprite);
            this.removeChild(this.enemy.nameText);
            this.removeChild(this.enemy.hpText);
            this.removeChild(this.enemy.levelText);
        }

        this.enemy = new Enemy(enemyJson);
        this.addChild(this.enemy.mySprite);

        this.enemy.nameText = new cc.MenuItemFont("name:" + this.enemy.name);
        this.enemy.nameText.x = this.enemy.mySprite.x;
        this.enemy.nameText.y = this.enemy.mySprite.y - 100;
        this.addChild(this.enemy.nameText);

        this.enemy.hpText = new cc.MenuItemFont("hp:" + this.enemy.hp+"/"+this.enemy.hpMax);
        this.enemy.hpText.x = this.enemy.mySprite.x;
        this.enemy.hpText.y = this.enemy.mySprite.y - 130;
        this.addChild(this.enemy.hpText);

        this.enemy.levelText = new cc.MenuItemFont("level:" + this.enemy.level);
        this.enemy.levelText.x = this.enemy.mySprite.x;
        this.enemy.levelText.y = this.enemy.mySprite.y - 160;
        this.addChild(this.enemy.levelText);

        //enemy attack picture
        this.enemyAttackEffect = new cc.Sprite(res.quanhen_png);
        this.enemyAttackEffect.attr({
            x: size.width/9,
            y: size.height - size.height/2,
        });
        this.addChild(this.enemyAttackEffect);
        this.enemyAttackEffect.setVisible(0);
    },

    createHero: function (HeroJson) {

        if (this.hero) {
            this.removeChild(this.hero.mySprite);
            this.removeChild(this.hero.nameText);
            this.removeChild(this.hero.hpText);
            this.removeChild(this.hero.levelText);
        }

        this.hero = new Hero(HeroJson);
        this.hero.mySprite.setFlippedX(true);
        this.addChild(this.hero.mySprite);
        this.hero.nameText = new cc.MenuItemFont("name:" + this.hero.name);
        this.hero.nameText.x = 100;
        this.hero.nameText.y = this.hero.mySprite.y - 100;
        this.addChild(this.hero.nameText);
        this.hero.hpText = new cc.MenuItemFont("hp:" + this.hero.hp+"/"+this.hero.hpMax);
        this.hero.hpText.x = 100;
        this.hero.hpText.y = this.hero.mySprite.y - 130;
        this.addChild(this.hero.hpText);
        this.hero.levelText = new cc.MenuItemFont("level:" + this.hero.level);
        this.hero.levelText.x = 100;
        this.hero.levelText.y = this.hero.mySprite.y - 160;
        this.addChild(this.hero.levelText);
        this.hero.expText = new cc.MenuItemFont("exp:" + this.hero.exp);
        this.hero.expText.x = 100;
        this.hero.expText.y = this.hero.mySprite.y - 190;
        this.addChild(this.hero.expText);
        //hero attack picture
        this.heroAttackEffect = new cc.Sprite(res.daohen_png);
        this.heroAttackEffect.attr({
            //x: this.enemy.mySprite.x,
            //y: this.enemy.mySprite.y,
            x: size.width - size.width/9,
            y: size.height - size.height/2,
        });
        this.addChild(this.heroAttackEffect);
        this.heroAttackEffect.setVisible(0);
    },
    controlMusic: function (obj) {
        if (obj._selectedIndex == 0) {
            //open bgmusic and music effect
            //if(!this.hasOpenbgMusic){
            //    cc.audioEngine.playMusic(res.gameMusic_mp3,true);
            //    this.hasOpenbgMusic = true;
            //}else{
            //not find continue  to play music api銆傘�傘��,only resume music
            cc.audioEngine.resumeMusic()
            //}

            this.isOpenEffect = true;
        } else if (obj._selectedIndex == 1) {
            cc.audioEngine.pauseMusic(res.gameMusic_mp3);
            this.isOpenEffect = false;
        }
    },
    //when change hero or defeat enemy, trigger save
    save: function () {

        var heroText = gf.getObjJson(this.hero,true);
        //g.storage.setItem("gameRes",g);
        g.storage.setItem("hero", heroText);
        g.storage.setItem("currentHero", this.currentHero);
        g.storage.setItem("currentEnemy", this.currentEnemy);
    },
    upStair: function (btn) {
        if (this.currentEnemy > 0) {
            this.currentEnemy--;
            this.createEneny(enemyArray[this.currentEnemy]);
        } else {
            alert('this is the first checkpoint');
            return;
        }
    },
    upHero: function (btn) {
        var self = btn._parent;
        if (self.currentHero > 0) {
            self.currentHero--;
            self.createHero(heroArray[self.currentHero]);
            self.createEneny(enemyArray[self.currentEnemy]);
        } else {
            alert('this is the first hero');
            return;
        }
    },
    downStair: function (btn) {
        if (this.currentEnemy > this.enemyTotal) {
            alert('this is the last checkpoint');
            return;
        } else {
            this.currentEnemy++;
            this.createEneny(enemyArray[this.currentEnemy]);
        }
    },
    downHero: function (btn) {
        var self = btn._parent;
        if (self.currentHero > self.heroTotal) {
            alert('this is the last hero');
            return;
        } else {
            self.currentHero++;
            self.createHero(heroArray[self.currentHero]);
            self.createEneny(enemyArray[self.currentEnemy]);
        }
    },

    //skip hero or enemy detail scene
    propertyDetailShow: function (btn) {
        var self = btn._parent;
        self.isAutoFight = false;


        if (btn.name=="HeroPropertyDetailBtn") {
            //hero
            var heroText = gf.getObjJson(self.hero,true);
            cc.director.pushScene(new PropertyDetailScene(heroText));
        } else {
            var enemyText = gf.getObjJson(self.enemy,false);
            cc.director.pushScene(new PropertyDetailScene(enemyText));
        }

    },
    //obj translate to json锛宨f true, translate  hero锛宖alse translate enemy
//        if (isHero) {
//            var heroJson = {};
//            heroJson.type = this.hero.type;
//            heroJson.mySprite = heroArray[this.currentHero]["mySprite"];//
//            heroJson.name = this.hero.name;
//            heroJson.hp = this.hero.hp;
//            heroJson.level = this.hero.level;
//            heroJson.exp = this.hero.exp;
//            heroJson.expArr = this.hero.expArr;
//            heroJson.attackNumber = this.hero.attackNumber;
//            heroJson.defenseNumber = this.hero.defenseNumber;
//            heroJson.critical = this.hero.critical;
//            heroJson.dodge = this.hero.dodge;
//            heroJson.fiveElement = this.hero.fiveElement;
//            heroJson.hpGrow = this.hero.hpGrow;
//            heroJson.attackGrow = this.hero.attackGrow;
//            heroJson.defenseGrow = this.hero.defenseGrow;
//            var heroText = JSON.stringify(heroJson);
//            return heroText;
//        } else {
//            var enemyJson = {};
//            enemyJson.type = this.enemy.type;
//            enemyJson.mySprite = enemyArray[this.currentEnemy]["mySprite"];
//            enemyJson.name = this.enemy.name;
//            enemyJson.hp = this.enemy.hp;
//            enemyJson.level = this.enemy.level;
//            enemyJson.exp = this.enemy.exp;
//            enemyJson.attackNumber = this.enemy.attackNumber;
//            enemyJson.defenseNumber = this.enemy.defenseNumber;
//            enemyJson.critical = this.enemy.critical;
//            enemyJson.dodge = this.enemy.dodge;
//            enemyJson.fiveElement = this.enemy.fiveElement;
//            var enemyText = JSON.stringify(enemyJson);
//            return enemyText;
//        }
//    },
    FightOnce:function(btn){
        var self = btn._parent;
        self.isFightOnce = true;
//        self.schedule(self.Myupdate, 2, 1);
//        or
//        self.Myupdate();
    },
    shopShow:function(btn){
        var self = btn._parent;
        var heroText = gf.getObjJson(self.hero,true);
        //cc.director.runScene(new ShopScene(heroText));
        cc.director.pushScene(new ShopScene(heroText));
    },
    skillShow: function (btn) {
        var self = btn._parent;
        var heroText = gf.getObjJson(self.hero,true);
        cc.director.pushScene(new SkillTreeScene(heroText));
    },
});

var GameScene = cc.Scene.extend({
    onEnter: function () {
        this._super();
        var layer = new GameWorldLayer();
        this.addChild(layer);
    }
});

